package org.amos.core.frame.config.thread;

import cn.hutool.core.util.CharUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;

import java.util.Objects;

/**
 * @desc: 线程池 配置
 * @author: liubt
 * @date: 2022-08-08 13:21
 **/
@Slf4j
@EnableAsync
@Configuration
@RequiredArgsConstructor
public class ThreadPoolConfig implements AsyncConfigurer {

    /**
     * 异步方法执行的过程中抛出的异常捕获记录
     *
     * @return
     */
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (throwable, method, objects) -> {
            String msg = StrUtil.EMPTY;
            if (ObjectUtil.isNotEmpty(objects) && objects.length > 0) {
                msg = StrUtil.join(msg, "参数是：");
                for (int i = 0; i < objects.length; i++) {
                    msg = StrUtil.join(msg, objects[i], CharUtil.CR);
                }
            }
            if (Objects.nonNull(throwable)) {
                msg = StrUtil.join(msg, throwable);
            }
            log.error(msg, method.getDeclaringClass());
        };
    }
}
